import { memo, useCallback, useEffect, useState } from "react"
import styled from "@emotion/styled"
import { useSearchAction } from "@/features/useSearchAction"
import { formatCurrency } from "@/utils/format"
import { useModalSlideUp } from "@/features/useModal"
import ButtonRegular from "@/components/composite/ButtonRegular/main"
import InputMoneyText from "@/components/form_item/InputMoneyText"
import { useForm, FormProvider } from "react-hook-form"
import ModalSlideUp from "@/components/composite/ModalSlideUp/main"
import SelectAccountType from "@/pages/WithdrawAccounts/components/SelectAccountType"
import SelectWithdrawAccount from "./SelectWithdrawAccount"
import { useGetAccounts, useWithdraw } from "@/features/business"
import { resolveAssetImage } from "@/utils/common"
import { ACCOUNT_TYPE, WITHDRAW_ACCOUNT } from "@/pages/WithdrawAccounts/constants"
import { WalletAccountType } from "@/features/business/WithdrawAccounts/useGetAccounts"
import Svg, { SvgComponent } from "@/components/base/Svg"
import AccountCard from "./AccountCard"
import { useUserWallet } from "@/features/business/HomePage_deprecated/atoms_deprecated"
import { useGetFinanceChannelList } from "@/features/business"

const WithdrawContainer = styled.div`
    position: relative;
    background-color: rgba(242, 243, 245, 1);
    height: 624rem;
    display: flex;
    flex-direction: column;
    position: relative;
`
const WithdrawContent = styled.div`
    padding: 0 12rem;
`

const WithdrawTitle = styled.div`
    display: flex;
    justify-content: center;
    font-family: "Inter";
    font-weight: 500;
    font-size: 18rem;
    padding-top: 8rem;
    height: 72rem;
    letter-spacing: 0%;
    text-align: center;
    color: rgba(255, 255, 255, 0.95);
    margin-top: -12rem;
    position: relative;
    & > img {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 0;
    }
    & > span {
        position: relative;
    }
`

const OptionClose = styled(SvgComponent("pages/UserCenterPage/deposit/close.svg"))`
    width: 24rem;
    height: 24rem;
    position: absolute;
    top: 12rem;
    right: 12rem;
`

const WithdrawCard = styled.div`
    background-color: #ffffff;
    border-radius: 10rem;
    border: 1rem solid #ffffff;
    padding: 12rem;
    margin-bottom: 12rem;
`

const WithdrawCardTitle = styled.p`
    color: #131416;
    font-size: 16rem;
    font-weight: 500;
    line-height: 24rem;
    padding: 0;
    margin: 0 0 6rem 0;
    display: flex;
    align-items: center;
    justify-content: space-between;

    & > span:nth-child(2) {
        color: #054bf0;
        font-size: 14rem;
    }
`
const WithdrawHint = styled.p`
    color: #69728c;
    font-size: 12rem;
    font-weight: 400;
    line-height: 16rem;
    padding: 0;
    margin: 0;
    word-break: break-word;
    overflow-wrap: break-word;
    white-space: normal;
    hyphens: auto;
`

const CardAccountHint = styled.p`
    font-size: 12rem;
    font-weight: 400;
    font-family: "Gilroy";
    margin: 12rem 0 0;
    display: flex;
    align-items: center;
    & > span:nth-child(1) {
        color: #69728c;
        margin-right: 6rem;
    }
    & > span:nth-child(2) {
        color: #131416;
        font-weight: 400;
        margin-right: 6rem;
    }
    & > img {
        width: 16rem;
        height: 16rem;
    }
`
const CardAccountHintSvg = styled(SvgComponent("pages/UserCenterPage/withdraw/doubt.svg"))`
    width: 16rem;
    height: 16rem;
`
const BottomBlock = styled.div`
    padding: 12rem 12rem 32rem;
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
`
const AccountCardUnSelected = styled.div`
    border: 1rem dashed #ff1f57;
    height: 80rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: relative;
    border-radius: 8rem;

    & > span {
        position: absolute;
        bottom: 16rem;
        color: #ff356b;
        font-weight: 400;
        font-size: 14rem;
        line-height: 20rem;
        transform: translateY(50%);
    }
`
const AccountCardSvg = styled(SvgComponent("pages/UserCenterPage/withdraw/add.svg"))``

const SubmitButton = styled(ButtonRegular)`
    background: ${({ disabled }) =>
        disabled
            ? "linear-gradient(90deg, #FFADC2 0%, #FFADEB 100%)"
            : "linear-gradient(90deg, #FF3568 10%, #FF33CC 100%)"};

    width: 100%;
    height: 40rem;
    line-height: 40rem;
    font-family: "Gilroy";
    font-weight: 700;
    font-size: 16rem;
    text-align: center;
    color: ${({ disabled }) => (disabled ? "rgba(255, 255, 255, 1)" : "#ffffff")};
    box-shadow: none;
`

function Withdraw() {
    const { data: channels = [] } = useGetFinanceChannelList()
    const { data: accounts = [] } = useGetAccounts()
    const enabledAccount = accounts.filter((item) => item.status === 1)
    const { withdraw, loading } = useWithdraw()

    const { close } = useModalSlideUp("search-action")
    const { open: openModal, close: closeAccount } = useModalSlideUp("account-page")
    const [currentPayment, setCurrentPayment] = useState<WalletAccountType | undefined>()

    useEffect(() => {
        if (enabledAccount.length > 0) {
            setCurrentPayment(enabledAccount[0])
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [accounts])

    const { clearAction } = useSearchAction()
    const methods = useForm({
        defaultValues: {
            amount: "",
        },
    })

    const { setValue, getValues } = methods

    const handleClose = () => {
        close()
        clearAction()
        closeAccount()
    }

    const handleOpenModal = useCallback(
        (type: string) => {
            switch (type) {
                case "accountType":
                    openModal(
                        <SelectAccountType
                            accounts={enabledAccount}
                            channels={channels}
                            onClose={handleClose}
                        />,
                        {
                            closeOnClickMask: true,
                            closeOnEscape: false,
                        },
                    )
                    break
                case "withdrawAccount":
                    openModal(
                        <SelectWithdrawAccount
                            accounts={enabledAccount}
                            selectedAccount={currentPayment}
                            onSelect={setCurrentPayment}
                        />,
                        {
                            closeOnClickMask: false,
                            closeOnEscape: false,
                        },
                    )
                    break
                default:
                    break
            }
        },
        // eslint-disable-next-line react-hooks/exhaustive-deps
        [openModal, enabledAccount, currentPayment],
    )

    const handleSubmit = async () => {
        const amount = getValues("amount")
        if (!amount) return

        const data = {
            account_id: currentPayment?.id,
            amount: getValues("amount"),
        }

        const success = await withdraw(data)
        if (success) {
            handleClose()
        }
    }
    const { wallet, getUserWallet } = useUserWallet()
    const withdrawable = wallet.withdrawable ?? "0"
    useEffect(() => {
        getUserWallet()
    }, [getUserWallet])
    // 格式化余额
    const formattedBalance = formatCurrency(
        wallet.withdrawable ? parseFloat(wallet.withdrawable) : 0,
        {
            currency: "PHP",
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
        },
    )

    return (
        <>
            <WithdrawContainer>
                <WithdrawTitle>
                    <img
                        src={resolveAssetImage("pages/UserCenterPage/deposit/deposit_head.webp")}
                        alt="header"
                    />
                    <span>Withdraw</span>
                </WithdrawTitle>
                <OptionClose onClick={handleClose}></OptionClose>
                <WithdrawContent>
                    <WithdrawCard>
                        <WithdrawCardTitle>
                            <span>Withdraw Account</span>
                            {enabledAccount?.length > 0 && (
                                <span onClick={() => handleOpenModal(WITHDRAW_ACCOUNT)}>
                                    Change
                                </span>
                            )}
                        </WithdrawCardTitle>
                        {enabledAccount?.length > 0 && <AccountCard data={currentPayment} />}
                        {enabledAccount?.length === 0 && (
                            <AccountCardUnSelected onClick={() => handleOpenModal(ACCOUNT_TYPE)}>
                                <AccountCardSvg />
                                <span>Add Withdraw account</span>
                            </AccountCardUnSelected>
                        )}
                    </WithdrawCard>
                    <WithdrawCard>
                        <WithdrawCardTitle>Withdraw Amount</WithdrawCardTitle>
                        <FormProvider {...methods}>
                            <InputMoneyText
                                fieldName={"amount"}
                                placeholder={"Minimum Amount: 100"}
                                iconSrc={<Svg src="pages/UserCenterPage/deposit/peso.svg" />}
                                min={100}
                                customText={"Withdraw All"}
                                customOnClick={() => {
                                    setValue("amount", withdrawable)
                                }}
                            />
                        </FormProvider>
                        <CardAccountHint>
                            <span>Withdrawable balance:</span>
                            <span>{formattedBalance}</span>
                            <CardAccountHintSvg />
                        </CardAccountHint>
                    </WithdrawCard>
                    <WithdrawHint lang="en">
                        Generally receive withdraw in 5 minutes; <br />
                        If your withdraw has not been received exceed 5 minutes, <br />
                        please contact customer service and provide your withdraw receipt.
                    </WithdrawHint>
                </WithdrawContent>
                <BottomBlock>
                    <SubmitButton
                        disabled={!getValues("amount") || !currentPayment}
                        onClick={handleSubmit}
                    >
                        Withdraw now
                    </SubmitButton>
                </BottomBlock>
            </WithdrawContainer>
            <ModalSlideUp familyName="account-page" />
        </>
    )
}

export default memo(Withdraw)
